package org.orqlog.dubbo.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.*;
import org.orqlog.Utils.IpUtil;

import java.util.*;

@Activate(group = {CommonConstants.CONSUMER})
public class MonitorFilter implements Filter{
    private List<Long> aTimes = new ArrayList<Long>();
    private List<Long> bTimes = new ArrayList<Long>();
    private List<Long> cTimes = new ArrayList<Long>();
    private Long lastTime = System.currentTimeMillis();

    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
//        System.out.println("Invoked method: " + invocation.getMethodName());
        String tMetohd = invocation.getMethodName();
        Long sTime = System.currentTimeMillis();
        try {
            return invoker.invoke(invocation);
        } finally {
            Long eTime = System.currentTimeMillis();
            // 计算耗时并加入到列表
            Long uTime = eTime - sTime;
            if (tMetohd == "methodA") {
                aTimes.add(uTime);
            }
            if (tMetohd == "methodB") {
                bTimes.add(uTime);
            }
            if (tMetohd == "methodC") {
                cTimes.add(uTime);
            }
            if (eTime - lastTime > 5000) {
                Long[] zTimes;
                zTimes = getTpTimes(aTimes);
                System.out.println("methodA T90: " + zTimes[0] + ", T99: " + zTimes[1]);
                zTimes = getTpTimes(bTimes);
                System.out.println("methodB T90: " + zTimes[0] + ", T99: " + zTimes[1]);
                zTimes = getTpTimes(cTimes);
                System.out.println("methodC T90: " + zTimes[0] + ", T99: " + zTimes[1]);

                // 重置请求时间记录
                aTimes = new ArrayList<Long>();
                bTimes = new ArrayList<Long>();
                cTimes = new ArrayList<Long>();
                lastTime = eTime;
            }
        }
    }

    private Long[] getTpTimes(List<Long> tTimes)
    {
        ArrayList<Long> nTimes = new ArrayList<Long>(tTimes);
        Collections.sort(nTimes);
        int aIndex = (int) (nTimes.size() * 0.9);
        int bIndex = (int) (nTimes.size() * 0.99);

        Long[] result = new Long[2];
        result[0] = nTimes.get(aIndex);
        result[1] = nTimes.get(bIndex);
        return result;
    }
}
